Imports System.IO

Public Class MainForm

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub btnStartImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartImport.Click
        lblStatus.Text = String.Empty


        My.Settings.StorePassword = Me.PasswordField.Text
        My.Settings.StoreUsername = Me.UsernameField.Text.Trim
        My.Settings.StoreUrl = Me.SiteURLField.Text.Trim
        My.Settings.Save()

        Dim fd As New OpenFileDialog
        fd.FileName = My.Settings.SourceFile
        If fd.ShowDialog() = Windows.Forms.DialogResult.OK Then
            My.Settings.SourceFile = fd.FileName
        Else
            Me.lblStatus.Text = ""
            Exit Sub
        End If
        fd = Nothing

        Try
            ' Make sure we're starting with a file
            Logging.CloseLogFile()
            Logging.WriteLine("Starting Import at " & DateTime.Now)

            Me.lblStatus.Text = "Starting Import..."
            Application.DoEvents()

            If File.Exists(My.Settings.SourceFile) Then
                Logging.WriteLine("Reading Import File...")
                Me.lblStatus.Text = "Reading Import File..."
                Application.DoEvents()

                Dim lines() As String = File.ReadAllLines(My.Settings.SourceFile)
                If lines IsNot Nothing Then
                    If lines.Length > 0 Then

                        Logging.Write("Reading Column Names...")
                        Me.lblStatus.Text = "Reading Column Names..."
                        Application.DoEvents()

                        Dim cols() As Core.MappedColumn = MapperUtils.ParseColumns(lines(0))
                        If cols IsNot Nothing Then

                            If cols.Length < 1 Then
                                Logging.WriteLine("No valid columns were found!")
                                MsgBox("No valid columns could be located!")
                                Exit Sub
                            End If

                            If cols(0).ColumnName <> "bvin" Then
                                Logging.WriteLine("The first column name is required to be ""bvin"".")
                                MsgBox("The first column name is required to be ""bvin"".")
                                Exit Sub
                            End If

                            Logging.WriteLine("Determining Import Type...")
                            Me.lblStatus.Text = "Determining Import Type..."
                            Application.DoEvents()

                            ' Determine Import Type
                            Dim iType As ImportSelection = MapperUtils.FindImportType(cols)

                            ' Create Transltor
                            Dim t As Core.Modules.Translator = Nothing
                            Select Case iType
                                Case ImportSelection.None
                                    ' 
                                    Logging.WriteLine("Import Type = None")
                                Case ImportSelection.Categories
                                    Logging.WriteLine("Import Type = Categories")
                                    t = New Core.Modules.CategoryTranslator
                                Case ImportSelection.Products
                                    Logging.WriteLine("Import Type = Products")
                                    t = New Core.Modules.ProductTranslator
                                Case ImportSelection.ProductTypes
                                    Logging.WriteLine("Import Type = Product Types")
                                    MsgBox("Product Type Import is not yet supported")
                                    't = New Core.Modules.CategoryTranslator
                                Case ImportSelection.Users
                                    Logging.WriteLine("Import Type = Users")
                                    t = New Core.Modules.UserTranslator
                            End Select

                            If t Is Nothing Then
                                Logging.WriteLine("Unable to determine import type!")
                                MsgBox("Unable to determine import type!")
                                Exit Sub
                            Else
                                Me.lblStatus.Text = String.Empty
                                Application.DoEvents()
                                ' Get Result
                                AddHandler t.StatusChanged, AddressOf t_StatusChanged
                                If t.Import(lines, cols) Then
                                    Logging.WriteLine("Overall Result = TRUE")
                                Else
                                    Logging.WriteLine("Overall Result = FALSE")
                                End If
                                RemoveHandler t.StatusChanged, AddressOf t_StatusChanged
                            End If


                        Else
                            Logging.WriteLine("No columns were found in the import file.")
                            Me.lblStatus.Text = "No columns were found in the import file."
                            Application.DoEvents()
                            Exit Sub
                        End If
                    Else
                        Logging.WriteLine("Import file was empty!")
                        Me.lblStatus.Text = "Import file was empty!"
                        Application.DoEvents()
                        Exit Sub
                    End If
                Else
                    Logging.WriteLine("Unable to read import file!")
                    Me.lblStatus.Text = "Unable to read import file!"
                    Application.DoEvents()
                    Exit Sub
                End If
            Else
                Logging.WriteLine("The file to import from could not be found!")
                MsgBox("The file to import from was not found!")
                Exit Sub
            End If

        Catch ex As Exception
            Logging.WriteLine("Exception: " & ex.Message & " - " & ex.StackTrace & " " & ex.TargetSite.Name)
            MsgBox("Import Error: " & ex.Message & " - " & ex.StackTrace & " " & ex.TargetSite.Name)
        Finally
            Me.Show()
            Logging.CloseLogFile()
            ' Show Log here
            Dim v As New ExportView
            v.OutputText = File.ReadAllText(Logging.LogFileName)
            v.ShowDialog()
            v.Dispose()
        End Try
        'lblStatus.Text = String.Empty
    End Sub

    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        lblStatus.Text = String.Empty

        My.Settings.StorePassword = Me.PasswordField.Text
        My.Settings.StoreUsername = Me.UsernameField.Text.Trim
        My.Settings.StoreUrl = Me.SiteURLField.Text.Trim
        My.Settings.Save()        

        Try
            If ExportSelection.ShowDialog() = Windows.Forms.DialogResult.OK Then
                ' Create Translator and Export

                Dim t As Core.Modules.Translator = Nothing

                Select Case My.Settings.ExportMode
                    Case 0 ' Category
                        t = New Core.Modules.CategoryTranslator
                    Case 1 ' Products
                        t = New Core.Modules.ProductTranslator
                    Case 2 ' Users
                        t = New Core.Modules.UserTranslator
                    Case Else
                        t = New Core.Modules.CategoryTranslator
                End Select

                If t Is Nothing Then
                    MsgBox("Unable to determine export request type. See Administrator for Assistance.")
                Else
                    AddHandler t.StatusChanged, AddressOf t_StatusChanged
                    If t.Export() Then
                        Me.lblStatus.Text = "Finished!"
                        Application.DoEvents()
                    Else
                        Me.lblStatus.Text = "Finished with errors."
                        Application.DoEvents()
                    End If
                    RemoveHandler t.StatusChanged, AddressOf t_StatusChanged
                End If
            End If
        Catch ex As Exception
            MsgBox("Export Error: " & ex.Message & " - " & ex.StackTrace & " " & ex.TargetSite.Name)
        Finally
            Me.Show()
        End Try
        'lblStatus.Text = String.Empty
    End Sub

    Private Sub t_StatusChanged(ByVal sender As Object, ByVal args As Core.Modules.Translator.TranslatorEventArgs)
        Me.lblStatus.Text = args.Message
        Application.DoEvents()
    End Sub
End Class